import { showDialog } from 'vant';
const intervalTime = 10000;
let timer = null

let oldFiles = {}
getFilesName().then(res => {
    oldFiles = res
    timer = setInterval(checkForUpdates, intervalTime);
});

async function checkForUpdates() {
    getFilesName().then(res => {
        const scriptsList = res.scriptsList
        const linksList = res.linksList
        for (const script of scriptsList) {
            if (!oldFiles.scriptsList.has(script)) {
                updatePage(script);
                return;
            }
        }

        for (const link of linksList) {
            if (!oldFiles.linksList.has(link)) {
                updatePage(link);
                return;
            }
        }
    });
}

function getScriptUrls(htmlContent) {
    const scriptUrls = [];
    const scriptTags = htmlContent.match(/<script[^>]*src="([^"]*)"[^>]*>/g) || [];
    for (const tag of scriptTags) {
        const match = tag.match(/src="([^"]*)"/);
        if (match && match[1] && !match[1].includes("?") && match[1].endsWith(".js")) {
            scriptUrls.push(match[1].split("/").pop());
        }
    }
    return scriptUrls;
}

function getLinkUrls(htmlContent) {
    const linkUrls = [];
    const linkTags = htmlContent.match(/<link[^>]*href="([^"]*)"[^>]*>/g) || [];
    for (const tag of linkTags) {
        const match = tag.match(/href="([^"]*)"/);
        if (match && match[1] && !match[1].includes("?") && match[1].endsWith(".css")) {
            linkUrls.push(match[1].split("/").pop());
        }
    }
    return linkUrls;
}

function updatePage(name) {
    clearInterval(timer);
    showDialog({
        message: '新版本已经发布，请点击确定获取最新版本！！！',
    }).then(() => {
        window.location.reload()
    });
}

async function getFilesName() {
    // 防止从磁盘中获取缓存
    const response = await fetch(`./index.html?timestamp=${Date.now()}`);
    const htmlContent = await response.text();

    const scriptsList = new Set(getScriptUrls(htmlContent));
    const linksList = new Set(getLinkUrls(htmlContent));
    return {
        scriptsList,
        linksList,
    };
}